package com.ztf0337.mycurriculumdesign.service;

import android.content.Context;

import com.ztf0337.mycurriculumdesign.dao.OrderDao;
import com.ztf0337.mycurriculumdesign.dao.RentDao;
import com.ztf0337.mycurriculumdesign.dao.UserDao;
import com.ztf0337.mycurriculumdesign.database.AppDatabase;
import com.ztf0337.mycurriculumdesign.entity.User;

import java.util.List;

public class UserService {

    private final UserDao userDao;
    private final RentDao rentDao;
    private final OrderDao orderDao;
    public UserService(Context context) {
        AppDatabase db = AppDatabase.getInstance(context);
        this.userDao = db.userDao();
        this.rentDao = db.rentDao();
        this.orderDao = db.orderDao();
    }

    /**
     *
     * @param phone
     * @param password
     * @return 0成功-1不存在-2密码错误-3管理
     */
    public Long login(String phone, String password) {

        User user = userDao.getUserByPhone(phone);
        if (user == null) {
            return -1L;
        }
        if (!user.getPassword().equals(password)) {
            return -2L;
        }
        if (user.getRoot()) {
            return -3L;
        }
        if (!user.getStatus()) {
            return -4L;
        }
        return user.getId();
    }

    /**
     *
     * @param user
     * @return 0成功1重复
     */
    public int register(User user) {
        if (userDao.getUserByPhone(user.getPhone()) != null) {
            return 1;
        }
        userDao.insert(user);
        return 0;
    }

    public User getUserById(Long id) {
        return userDao.getUserById(id);
    }

    public void updateUser(User user){
        userDao.update(user);
    }

    public List<User> getAll() {
        return userDao.getAllUser();
    }

    public List<User> searchUser(String phone){
        return userDao.searchAllUser(phone);
    }

    public void deleteUser(User user) {

        userDao.delete(user);
        rentDao.deleteRentsByUserId(user.getId());
        orderDao.deleteOrdersByUserId(user.getId());
    }



}
